package com.zsq.demo01.controller;

import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/testLock")
public class TestLockController {

    private static Logger logger = LoggerFactory.getLogger(TestLockController.class);

    @Autowired
    private RedissonClient redissonClient;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping("/getLock")
    public String getLock() {
        String key = "test_lock_001";
        String goods_key = "test_amount";
//        logger.debug("---一个客户端进来了");

        //先判断数量是否大于0
        String surplus = redisTemplate.opsForValue().get(goods_key);
        if("0".equals(surplus)){
            return "商品太抢手，没有了！";
        }
        //先减一个商品数量
        Long decrement = redisTemplate.opsForValue().decrement(goods_key);
        if(decrement < 0){
//            数量加到0
            redisTemplate.opsForValue().increment(goods_key);
            return "商品秒没啦";
        }

//        RLock lock = redissonClient.getLock(key);
        try {
            //加锁
//            lock.lock();
//            logger.debug("上锁了");
            //处理业务
//            logger.debug("当前线程：{}", Thread.currentThread().getName());

            logger.debug("---完成业务");
        }finally {
            //释放锁
//            lock.unlock();
        }
        return "ok";
    }

}
